import React, { Component } from 'react'
import { Route } from 'react-router'
import { TabBar } from 'antd-mobile'
import './index.scss'

import Index from '../Index'

const HouseList = React.lazy(() => import('../HouseList'))
const News = React.lazy(() => import('../News'))
const Profile = React.lazy(() => import('../Profile'))

//tab栏数据
const tabItems = [
  {
    title: '首页',
    icon: 'icon-ind',
    path: '/home',
  },
  {
    title: '找房',
    icon: 'icon-findHouse',
    path: '/home/list',
  },
  {
    title: '咨询',
    icon: 'icon-infom',
    path: '/home/news',
  },
  {
    title: '我的',
    icon: 'icon-my',
    path: '/home/profile',
  },
]

export default class Home extends Component {
  state = {
    //控制默认选中的tab标签
    selectedTab: '',
  }

  componentDidMount() {
    this.setState({ selectedTab: this.props.location.pathname })
  }

  componentDidUpdate(prevProps) {
    /* 对于前路由和现旅游的判断比较 对于tab的选中值进行重新选择 */
    if (prevProps.location.pathname !== this.props.location.pathname) {
      this.setState({
        selectedTab: this.props.location.pathname,
      })
    }
  }

  // 循环渲染tab栏函数
  renderTabBarItem() {
    return tabItems.map((item) => (
      <TabBar.Item
        title={item.title}
        key={item.title}
        i
        icon={<i className={`iconfont ${item.icon}`}></i>}
        selectedIcon={<i className={`iconfont ${item.icon}`}></i>}
        selected={this.state.selectedTab === item.path}
        onPress={() => {
          this.setState({
            selectedTab: item.path,
          })
          //路由跳转
          this.props.history.push(item.path)
        }}
      />
    ))
  }
  render() {
    return (
      <div className="home">
        {/* 配置子路由 */}
        <Route exact path="/home" component={Index}></Route>
        <Route path="/home/list" component={HouseList}></Route>
        <Route path="/home/news" component={News}></Route>
        <Route path="/home/profile" component={Profile}></Route>
        {/* 底部Tab栏 */}
        <TabBar tintColor="#2b9776" barTintColor="white" noRenderContent={true}>
          {this.renderTabBarItem()}
        </TabBar>
      </div>
    )
  }
}
